package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.entity.login.VerifyReturn;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * 注册
 */

public class RegistActivity extends BaseActivity {
    @BindView(R.id.bg)
    RelativeLayout bg;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.et_regist_telephone)
    EditText etRegistTelephone;
    @BindView(R.id.et_regist_verify)
    EditText etRegistVerify;
    @BindView(R.id.tv_regist_verify)
    TextView tvRegistVerify;
    @BindView(R.id.iv_regist_telephone_delete)
    ImageView ivRegistTelephoneDelete;
    @BindView(R.id.et_regist_password)
    EditText etRegistPassword;
    @BindView(R.id.iv_regist_show_or_hide)
    ImageView ivRegistShowOrHide;
    @BindView(R.id.cb_regist_fuwutiaokuan)
    CheckBox cbRegistFuwutiaokuan;
    @BindView(R.id.tv_regist_fuwutiaokuan)
    TextView tvRegistFuwutiaokuan;
    @BindView(R.id.btn_regist_regist)
    Button btnRegistRegist;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.divider)
    TextView divider;

    private Context mContext;
    /**
     * 是否显示密码
     */
    private boolean isShowPassword = false;
    /**
     * 服务条款是否被勾选
     */
    private boolean isFuWuTiaoKuanChecked = true;

    /**
     * 服务器返回的验证码
     */
    private String code = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
        initListener();
        bg.setBackgroundColor(getResources().getColor(R.color.transparent));
        next.setText("登录");
        next.setTextColor(getResources().getColor(R.color.common_green));
        next.setVisibility(View.VISIBLE);
        //不可点击下一步，获取到验证码后才可点击
        btnRegistRegist.setEnabled(false);
        btnRegistRegist.setAlpha(0.5f);
        divider.setVisibility(View.GONE);
    }

    private void initListener() {
        //服务条款checkbox监听事件
        cbRegistFuwutiaokuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    isFuWuTiaoKuanChecked = true;
                } else {
                    isFuWuTiaoKuanChecked = false;
                }
            }
        });

        //监听手机号控件删除按钮显示与隐藏
        etRegistTelephone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (etRegistTelephone.getText().toString().length() > 0) {
                    ivRegistTelephoneDelete.setVisibility(View.VISIBLE);
                } else {
                    ivRegistTelephoneDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @OnClick({R.id.iv_regist_telephone_delete, R.id.iv_regist_show_or_hide, R.id.btn_regist_regist, R.id.back, R.id.next, R.id.tv_regist_verify, R.id.tv_regist_fuwutiaokuan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back://返回按钮
                JumpHelper.finish(mContext);
                break;
            case R.id.next://登录
                JumpHelper.jump(RegistActivity.this, LoginActivity.class, true);
                break;
            case R.id.iv_regist_telephone_delete://清除手机号
                etRegistTelephone.setText("");
                break;
            case R.id.iv_regist_show_or_hide://显示与隐藏密码
                showOrHidePassword();
                break;
            case R.id.tv_regist_verify://获取验证码
                checkAndSendMobileCode();
                break;
            case R.id.btn_regist_regist://注册
                //手机号
                if (TextUtils.isEmpty(etRegistTelephone.getText().toString())) {
                    showToast("请输入手机号");
                    return;
                }
                //是否是正确的手机号判断
                if (!Utils.isTruePhone(etRegistTelephone.getText().toString())) {
                    showToast("请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(etRegistVerify.getText().toString())) {
                    showToast("请输入验证码");
                    return;
                }
                //验证码确认
                if (!code.equals(etRegistVerify.getText().toString())) {
                    showToast("请输入正确的验证码");
                    return;
                }
                if (TextUtils.isEmpty(etRegistPassword.getText().toString())) {
                    showToast("请输入密码");
                    return;
                }
                if (!isFuWuTiaoKuanChecked) {
                    showToast("请勾选服务条款");
                    return;
                }
                // 然后跳转完善资料页面
                Intent intent = new Intent(RegistActivity.this, PerfectInfomationActivity.class);
                intent.putExtra("mobile", etRegistTelephone.getText().toString());//手机号
                intent.putExtra("mobileCode", etRegistVerify.getText().toString());//验证码
                intent.putExtra("password", etRegistPassword.getText().toString());//密码
                JumpHelper.jump(RegistActivity.this, intent, true);
                break;
            case R.id.tv_regist_fuwutiaokuan://服务条款
                Intent fuwutiaokuanIntent = new Intent(RegistActivity.this, WebActivity.class);
                fuwutiaokuanIntent.putExtra("title", "服务条款");
                fuwutiaokuanIntent.putExtra("url", GlobalUrl.FUWUTIAOKUAN_URL);
                JumpHelper.jump(RegistActivity.this, fuwutiaokuanIntent, false);
                break;
        }
    }

    /**
     * 检测手机号是否注册过了，没有注册过就发送验证码
     */
    private void checkAndSendMobileCode() {
        //手机号
        if (TextUtils.isEmpty(etRegistTelephone.getText().toString())) {
            showToast("请输入手机号");
            return;
        }
        //是否是正确的手机号判断
        if (!Utils.isTruePhone(etRegistTelephone.getText().toString())) {
            showToast("请输入正确的手机号");
            return;
        }
        int type = 1;//1，注册；2，找回密码
        String mobile = etRegistTelephone.getText().toString().trim();//手机号
        fromNetwork.getValicode(type, mobile).compose(new RxActivityHelper<VerifyReturn>().ioMain(RegistActivity.this, true))
                .subscribe(new MySubscribe<VerifyReturn>(mContext, true) {
                    @Override
                    protected void success(VerifyReturn resultBean) {
                        if (resultBean.data != null) {
                            showToast("验证码请求成功");
                            code = resultBean.data;//验证码
                            //获取到验证码后，可点击下一步
                            btnRegistRegist.setAlpha(1);
                            btnRegistRegist.setEnabled(true);
                            refreshSendMobileCodeBtn();
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    /**
     * 显示与隐藏密码
     */
    private void showOrHidePassword() {
        if (isShowPassword) {//当前状态是显示密码，置为隐藏密码
            isShowPassword = false;
            ivRegistShowOrHide.setImageResource(R.mipmap.ic_mima_hide);
            //隐藏密码
            etRegistPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {//当前状态是隐藏密码，置为显示密码
            isShowPassword = true;
            ivRegistShowOrHide.setImageResource(R.mipmap.ic_mima_show);
            //显示密码
            etRegistPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }

    /**
     * 刷新获取验证码按钮
     */
    private void refreshSendMobileCodeBtn() {
        Utils.countDown(60)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        //开始计时
                        //获取验证码不可点击
                        tvRegistVerify.setBackgroundResource(R.drawable.shape_rectangle_green);
                        tvRegistVerify.setEnabled(false);
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        //计时完成
                        //获取验证码可点击
                        tvRegistVerify.setBackgroundResource(R.drawable.shape_rectangle_green);
                        tvRegistVerify.setText("获取");
                        tvRegistVerify.setEnabled(true);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        //当前计时
                        //刷新获取验证码按钮
                        tvRegistVerify.setText(integer + "S");
                    }
                });
    }
}
